package com.chenyuxin.ilp.ai.tool;
import com.chenyuxin.ilp.ai.util.PdfParser;
import com.chenyuxin.ilp.mapper.file.FileMetaMistakeMapper;
import com.chenyuxin.ilp.model.entity.file.FileMetaMistake;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Component
public class MistakeMistakeTool {
    @Autowired
    private FileMetaMistakeMapper fileMetaMistakeMapper;
    @Autowired
    private MinioClient minioClient;
    @Value("${minio.bucket.files}")
    private String bucket;

    @Tool("获取错题文件内容")
    public String getMistakeText(@P("错题文件id")Long fileId,@P("用户id")String userId) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        LambdaQueryWrapper<FileMetaMistake> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FileMetaMistake::getUserId,userId)
                .eq(FileMetaMistake::getId,fileId);
        FileMetaMistake fileMetaMistake = fileMetaMistakeMapper.selectOne(wrapper);
        if(fileMetaMistake==null){
            return "文件不存在";
        }
        String extension = fileMetaMistake.getFileName().substring(fileMetaMistake.getFileName().lastIndexOf("."));
        String objectName = "/"+userId+"/mistake/"+fileMetaMistake.getFolderId()+"/"+fileMetaMistake.getId()+extension;
        InputStream pdfStream = minioClient.getObject(
                GetObjectArgs.builder()
                        .bucket(bucket)
                        .object(objectName)
                        .build()
        );
        String text = PdfParser.extractTextFromPdf(pdfStream);
        return text;
    }
}
